import { Button, Form, Input, InputNumber, Modal, Select, SelectProps, Switch, TreeSelect, message } from "antd";
import { GFS } from "@/hooks/useAssignGlobalProps";
import { useForm } from "antd/es/form/Form";
import { useEffect, useMemo, useState } from "react";
import { saveMenu, getPageList } from "../../interfaces";
import { PageDataType } from "../pageManager";
import { MenuDataType } from "./index";
import { cloneDeep } from "lodash-es";
interface TreeNode {
  id: number;
  label: string;
  children?: TreeNode[];
  isFolder: boolean;
}
interface AddMenuModalProps {
  isOpen: boolean;
  handleClose: Function;
  freshPage: Function;
  editObj: MenuDataType | null;
  dataSource: TreeNode[];
}

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};

export interface AddMenu {
  id: number | null;
  label: string;
  path: string;
  icon: string;
  isFolder: boolean;
  parentId: number;
  sort: number;
}

export function AddMenuModal(props: AddMenuModalProps) {
  const { isOpen, handleClose, freshPage, editObj, dataSource } = props;
  const hasChildren = useMemo(()=>{
    return Array.isArray(editObj?.children) && editObj.children.length > 0
  }, [editObj])
  const initialValues: AddMenu = {
    id: null,
    label: "",
    path: "",
    icon: "",
    isFolder: false,
    parentId: 0,
    sort: 100,
  };
  const [form] = useForm<AddMenu>();
  const [pageOptions, setPageOptions] = useState<Record<string, string>[]>([]);
  const [requirePath, setRequirePath] = useState(false);

  const nodeTree = useMemo(()=>{
    const rawData = {
      id: 0,
      label: "根节点",
      isFolder: true,
      children: cloneDeep(dataSource)
    }
    function loopFn(node: TreeNode){
      if(Array.isArray(node.children)){
        node.children = node.children.filter(ele=>ele.isFolder)
        node.children.forEach(loopFn)
      }
    }
    loopFn(rawData)
    return [rawData]
  },[dataSource])
  
  useEffect(() => {
    if (isOpen) {
      getPageData();
      const renderObj = editObj || initialValues
      form.setFieldsValue(renderObj);
      setRequirePath(!renderObj.isFolder);
    }
  }, [isOpen]);
  async function getPageData() {
    const res = await getPageList(1, 10000);
    const data = res.data.data.map((cell: PageDataType) => {
      return {
        label: cell.label,
        value: cell.path,
        icon: cell.icon,
      };
    });
    setPageOptions(data);
  }

  const handleOk = async function () {
    await form.validateFields();
    const values = form.getFieldsValue();
    const res = await saveMenu({...values, id: editObj ? editObj.id : null});

    if (res.status === 201 || res.status === 200) {
      GFS.message.success(res.data.message);
      setTimeout(() => {
        form.resetFields();
        handleClose();
        freshPage();
      }, 700);
    }
  };

  function handlePathSelect(_: string, option: Record<string, string>) {
    const { label, value, icon } = option;
    form.setFieldsValue({
      label,
      path: `/legoPage/${value}`,
      icon,
    });
  }

  function handleIsFolderChange(state: boolean) {
    setRequirePath(!state);
    if (state) {
      form.setFieldValue("path", "");
    }
  }
  return (
    <Modal
      title={`${editObj ? "编辑" : "新增"}菜单`}
      open={isOpen}
      onOk={handleOk}
      onCancel={() => handleClose()}
      destroyOnClose
      width="480px"
    >
      <Form form={form} colon={false} {...layout}>
        <Form.Item label="名称" name="label" rules={[{ required: true, message: "请输入名称!" }]}>
          <Input />
        </Form.Item>
        <Form.Item label="路径" name="path" rules={[{ required: requirePath, message: "请输入路径!" }]}>
          <Input
            allowClear
            addonAfter={
              <Select
                options={pageOptions}
                placeholder="选择路径"
                onSelect={handlePathSelect}
                style={{ width: "120px" }}
                disabled={hasChildren || !requirePath}
              />
            }
            disabled={!requirePath}
          />
        </Form.Item>
        <Form.Item label="图标" name="icon">
          <Input />
        </Form.Item>
        <Form.Item label="排序" name="sort">
          {/* <Input /> */}
          <InputNumber min={1} max={100}/>
        </Form.Item>
        <Form.Item label="父节点名称" name="parentId">
          <TreeSelect
            showSearch
            style={{ width: '100%' }}
            fieldNames={{value: "id"}}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            placeholder="请选择父节点"
            disabled={editObj?true:false}
            treeDefaultExpandAll
            onChange={()=>{}}
            treeData={nodeTree}
          />
        </Form.Item>
        <Form.Item label="是否文件夹" name="isFolder">
          <Switch onChange={handleIsFolderChange} disabled={hasChildren}/>
        </Form.Item>
      </Form>
    </Modal>
  );
}
